from constants.all import parse_params
from constants.dopple import DOPPLE
from modules.dopple import integrate_old_dopple
from modules.integrate import integrate_data
from datetime import datetime
import pandas as pd
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
from service.mail import send_email
from service.utils import config, BASE_DIR, logger
import os
import click


# 将数据保存到excel
def save_excel(data=[]):
    try:
        file_name = f'{datetime.now().strftime("%Y%m%d%H%M%S")}.xlsx'
        if len(data) > 0:
            df = pd.DataFrame(data)
            try:
                df = df.sort_values(by="非大会员利润率", ascending=False)
            finally:
                wb = Workbook()
                ws = wb.active
                ws.title = "cs2数据统计"
                for r in dataframe_to_rows(df, index=False, header=True):
                    ws.append(r)
                wb.save(os.path.join(BASE_DIR, "data", file_name))
        logger.info(f"数据成功保存到{file_name}！")
        return file_name
    except Exception as e:
        logger.error(f"数据写入失败！{e}")
        return None


# 交互式主流程
@click.command()
def main_interactive():
    # 获取交互参数
    is_dopple = click.confirm("是否查询多普勒?", default=True)
    click.echo("以下参数多个值之间用“,”分割")
    tags = click.prompt("请输入标签", type=str)
    wear = click.prompt(
        "请输入查询磨损(FN崭新, MW略磨, FT久经, WW破损, BS战痕)",
        type=str,
    )
    params = parse_params(tags.split(","), wear.split(","), {})
    is_email = click.confirm("是否发送邮件?", default=True)
    receiver = config.get("QQMAIL", "RECEIVER")
    if is_email:
        receiver = click.prompt("请输入收件人", type=str)
    click.echo(
        f"一共查询{(len(params) + len(DOPPLE)) if is_dopple else len(params)}个项目",
    )

    # 收集饰品数据
    dopple_data = []
    format_data = integrate_data(params)
    if is_dopple:
        dopple_data = integrate_old_dopple()
    data_all = format_data + dopple_data

    # 保存 & 发邮件
    table_name = save_excel(data_all)
    if is_email and table_name is not None:
        try:
            send_email(
                qq_email=config.get("QQMAIL", "SENDER"),
                auth_code=config.get("QQMAIL", "AUTHCODE"),
                recipient=receiver,
                subject="cs2数据统计",
                content="",
                file_path=os.path.join(BASE_DIR, "data", table_name),
            )
        except Exception as e:
            logger.error(f"邮件发送失败！{e}")


# 主流程
def main_flow():
    # 收集数据
    params = parse_params(["AK47"], ["FN"], {})
    dopple_data = integrate_old_dopple()
    format_data = integrate_data(params)
    data_all = format_data + dopple_data

    # 保存 & 发邮件
    table_name = save_excel(data_all)
    if table_name is not None:
        try:
            send_email(
                qq_email=config.get("QQMAIL", "SENDER"),
                auth_code=config.get("QQMAIL", "AUTHCODE"),
                recipient=config.get("QQMAIL", "RECEIVER"),
                subject="cs2数据统计",
                content="",
                file_path=os.path.join(BASE_DIR, "data", table_name),
            )
        except Exception as e:
            logger.error(f"邮件发送失败！{e}")


# 主函数
if __name__ == "__main__":
    # main_flow()
    main_interactive()
